import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'



Vue.use(VueRouter)

const routes = [
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import('../views/Detail.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/',
    name: 'Layout',
    redirect: '/article',
    component: () => import('../views/Layout.vue'),
    children: [
      {
        path: '/article',
        name: 'Article',
        component: () => import('../views/Article.vue'),
      },
      {
        path: '/collect',
        name: 'Collect',
        component: () => import('../views/Collect.vue'),
      },
      {
        path: '/like',
        name: 'Like',
        component: () => import('../views/Like.vue'),
      },
      {
        path: '/my',
        name: 'My',
        component: () => import('../views/My.vue'),
      },
    ]
  },
]

const router = new VueRouter({
  routes
})
// 路由导航守卫===路由钩子函数,路由地址发生改变时触发
//from 从哪里  to  到哪里   next()是否放行

const white = ["/login", "/register"]
//有token 就跳转 没有不跳 但是 login 注册 能跳

router.beforeEach((to, from, next) => {
  var token = getToken()
  if (token) {
    next()//放行
  } else {
    if (white.includes(to.path)) {//判断你去的地方是否 是 login 或者 注册页面
      next()
    } else {  // 不是的话去 跳转到登录页
      next("/login")
    }
  }

})


// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题

// push
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}



// replace
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return originalReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
export default router
